// 设备分享管理云对象
const crypto = require('crypto');

module.exports = {
	_before: function () {
		// 通用预处理器
		this.startTime = Date.now();
	},

	/**
	 * 创建设备分享
	 * @param {string} deviceId 设备ID
	 * @param {string} sharedUserEmail 被分享用户邮箱
	 * @param {array} permissions 权限列表
	 * @param {number} expireDays 过期天数（可选，默认30天）
	 * @returns {object} 分享结果
	 */
	async createShare({deviceId, sharedUserEmail, permissions = ['control', 'view'], expireDays = 30}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const ownerId = uid
		
		if (!deviceId || !ownerId || !sharedUserEmail) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where({
				_id: deviceId,
				owner_id: ownerId
			}).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '设备不存在或无权限分享'
				}
			}

			// 查找被分享用户
			const userResult = await db.collection('sh_user').where({
				email: sharedUserEmail
			}).get();

			if (userResult.data.length === 0) {
				return {
					errCode: 'USER_NOT_FOUND',
					errMsg: '被分享用户不存在'
				}
			}

			const sharedUser = userResult.data[0];

			// 检查是否已分享给该用户
			const existShareResult = await db.collection('sh_device_share').where({
				device_id: deviceId,
				shared_user_id: sharedUser._id
			}).get();

			if (existShareResult.data.length > 0) {
				return {
					errCode: 'ALREADY_SHARED',
					errMsg: '已分享给该用户'
				}
			}

			// 生成邀请码
			const inviteCode = crypto.createHash('md5').update(deviceId + sharedUser._id + Date.now()).digest('hex').substring(0, 8);

			// 计算过期时间
			const expireTime = new Date();
			expireTime.setDate(expireTime.getDate() + expireDays);

			// 创建分享记录
			const shareResult = await db.collection('sh_device_share').add({
				device_id: deviceId,
				owner_id: ownerId,
				shared_user_id: sharedUser._id,
				shared_user_email: sharedUserEmail,
				permissions,
				status: 0, // 待接受
				expire_time: expireTime,
				invite_code: inviteCode,
				create_time: new Date()
			});

			// 发送邀请消息
			await uniCloud.callFunction({
				name: 'message',
				data: {
					action: 'sendSystemMessage',
					targetUserId: sharedUser._id,
					type: 'device_share',
					title: '设备分享邀请',
					content: `用户邀请您使用设备：${deviceResult.data[0].device_name}`,
					data: {
						shareId: shareResult.id,
						deviceId,
						deviceName: deviceResult.data[0].device_name,
						inviteCode
					}
				}
			});

			return {
				errCode: 0,
				errMsg: '分享邀请已发送',
				data: {
					shareId: shareResult.id,
					inviteCode
				}
			}
		} catch (error) {
			console.error('创建设备分享失败:', error);
			return {
				errCode: 'CREATE_SHARE_FAILED',
				errMsg: '创建设备分享失败'
			}
		}
	},

	/**
	 * 接受分享邀请
	 * @param {string} shareId 分享ID
	 * @param {string} inviteCode 邀请码
	 * @returns {object} 接受结果
	 */
	async acceptShare({shareId, inviteCode}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!shareId || !userId || !inviteCode) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 查找分享记录
			const shareResult = await db.collection('sh_device_share').where({
				_id: shareId,
				shared_user_id: userId,
				invite_code: inviteCode
			}).get();

			if (shareResult.data.length === 0) {
				return {
					errCode: 'SHARE_NOT_FOUND',
					errMsg: '分享邀请不存在或邀请码错误'
				}
			}

			const share = shareResult.data[0];

			// 检查分享状态
			if (share.status !== 0) {
				return {
					errCode: 'SHARE_INVALID',
					errMsg: '分享邀请已处理'
				}
			}

			// 检查过期时间
			if (new Date() > new Date(share.expire_time)) {
				return {
					errCode: 'SHARE_EXPIRED',
					errMsg: '分享邀请已过期'
				}
			}

			// 更新分享状态
			await db.collection('sh_device_share').doc(shareId).update({
				status: 1, // 已接受
				accept_time: new Date()
			});

			// 更新设备的共享用户列表
			const deviceResult = await db.collection('sh_user_device').doc(share.device_id).get();
			if (deviceResult.data.length > 0) {
				const device = deviceResult.data[0];
				const sharedUsers = device.shared_users || [];
				if (!sharedUsers.includes(userId)) {
					sharedUsers.push(userId);
					await db.collection('sh_user_device').doc(share.device_id).update({
						shared_users: sharedUsers,
						update_time: new Date()
					});
				}
			}

			// 发送确认消息给设备拥有者
			await uniCloud.callFunction({
				name: 'message',
				data: {
					action: 'sendSystemMessage',
					userId: share.owner_id,
					type: 'device_share',
					title: '分享邀请已接受',
					content: `用户已接受您的设备分享邀请`,
					data: {
						deviceId: share.device_id,
						sharedUserId: userId
					}
				}
			});

			return {
				errCode: 0,
				errMsg: '接受分享成功'
			}
		} catch (error) {
			console.error('接受分享失败:', error);
			return {
				errCode: 'ACCEPT_SHARE_FAILED',
				errMsg: '接受分享失败'
			}
		}
	},

	/**
	 * 拒绝分享邀请
	 * @param {string} shareId 分享ID
	 * @returns {object} 拒绝结果
	 */
	async rejectShare({shareId}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!shareId || !userId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 查找并更新分享记录
			const updateResult = await db.collection('sh_device_share').where({
				_id: shareId,
				shared_user_id: userId,
				status: 0
			}).update({
				status: 2 // 已拒绝
			});

			if (updateResult.updated === 0) {
				return {
					errCode: 'SHARE_NOT_FOUND',
					errMsg: '分享邀请不存在或已处理'
				}
			}

			return {
				errCode: 0,
				errMsg: '拒绝分享成功'
			}
		} catch (error) {
			console.error('拒绝分享失败:', error);
			return {
				errCode: 'REJECT_SHARE_FAILED',
				errMsg: '拒绝分享失败'
			}
		}
	},

	/**
	 * 撤销设备分享
	 * @param {string} deviceId 设备ID
	 * @param {string} sharedUserId 被分享用户ID
	 * @returns {object} 撤销结果
	 */
	async revokeShare({deviceId, sharedUserId}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const ownerId = uid
		
		if (!deviceId || !ownerId || !sharedUserId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where({
				_id: deviceId,
				owner_id: ownerId
			}).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '设备不存在或无权限操作'
				}
			}

			// 更新分享状态
			await db.collection('sh_device_share').where({
				device_id: deviceId,
				owner_id: ownerId,
				shared_user_id: sharedUserId
			}).update({
				status: 3 // 已撤销
			});

			// 从设备的共享用户列表中移除
			const device = deviceResult.data[0];
			const sharedUsers = (device.shared_users || []).filter(id => id !== sharedUserId);
			await db.collection('sh_user_device').doc(deviceId).update({
				shared_users: sharedUsers,
				update_time: new Date()
			});

			// 发送通知给被撤销用户
			await uniCloud.callFunction({
				name: 'message',
				data: {
					action: 'sendSystemMessage',
					userId: sharedUserId,
					type: 'device_share',
					title: '设备分享已撤销',
					content: `设备 ${device.device_name} 的分享权限已被撤销`,
					data: {
						deviceId,
						deviceName: device.device_name
					}
				}
			});

			return {
				errCode: 0,
				errMsg: '撤销分享成功'
			}
		} catch (error) {
			console.error('撤销分享失败:', error);
			return {
				errCode: 'REVOKE_SHARE_FAILED',
				errMsg: '撤销分享失败'
			}
		}
	},

	/**
	 * 获取设备分享列表
	 * @param {string} deviceId 设备ID
	 * @returns {object} 分享列表
	 */
	async getDeviceShareList({deviceId}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const ownerId = uid
		
		if (!deviceId || !ownerId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where({
				_id: deviceId,
				owner_id: ownerId
			}).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '设备不存在或无权限查看'
				}
			}

			// 获取分享列表并关联用户信息
			const shareResult = await db.collection('sh_device_share')
				.aggregate()
				.match({
					device_id: deviceId,
					owner_id: ownerId
				})
				.lookup({
					from: 'user',
					localField: 'shared_user_id',
					foreignField: '_id',
					as: 'shared_user'
				})
				.unwind('$shared_user')
				.project({
					'shared_user.password': 0 // 不返回密码字段
				})
				.sort({create_time: -1})
				.end();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: shareResult.data
			}
		} catch (error) {
			console.error('获取设备分享列表失败:', error);
			return {
				errCode: 'GET_SHARE_LIST_FAILED',
				errMsg: '获取设备分享列表失败'
			}
		}
	},

	/**
	 * 获取用户收到的分享邀请
	 * @param {number} status 状态筛选（可选）
	 * @returns {object} 邀请列表
	 */
	async getUserShareInvites({status}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!userId) {
			return {
				errCode: 401,
				errMsg: '用户未登录'
			}
		}

		try {
			const db = uniCloud.database();
			
			let whereCondition = {
				shared_user_id: userId
			};
			
			if (status !== undefined) {
				whereCondition.status = status;
			}

			// 获取邀请列表并关联设备和拥有者信息
			const inviteResult = await db.collection('sh_device_share')
				.aggregate()
				.match(whereCondition)
				.lookup({
					from: 'device',
					localField: 'device_id',
					foreignField: '_id',
					as: 'device'
				})
				.lookup({
					from: 'user',
					localField: 'owner_id',
					foreignField: '_id',
					as: 'owner'
				})
				.unwind('$device')
				.unwind('$owner')
				.project({
					'owner.password': 0 // 不返回密码字段
				})
				.sort({create_time: -1})
				.end();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: inviteResult.data
			}
		} catch (error) {
			console.error('获取分享邀请失败:', error);
			return {
				errCode: 'GET_INVITES_FAILED',
				errMsg: '获取分享邀请失败'
			}
		}
	}
}
